package com.jar.exercise.网络编程.UDP连接.demo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

class Sender {
	public static void main(String[] args) {

		//套接字

		try (DatagramSocket ds = new DatagramSocket()) {
			//创建套接字
			String str = "hello，你好啊";
			byte[] bs = str.getBytes();
			//打包
			DatagramPacket dp = new DatagramPacket(bs, bs.length, InetAddress.getByName("192.168.234.1"), 12000);
			//发送数据包
			ds.send(dp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Server {
	public static void main(String[] args) {

		//创建一个服务的套接字

		try (DatagramSocket ds = new DatagramSocket(12000)) {
			//创建一个字节数组
			byte[] bs = new byte[1024];
			//创建一个空包
			DatagramPacket dp = new DatagramPacket(bs, bs.length);
			//接收
			ds.receive(dp);
			//获得接收的数据
			byte[] data = dp.getData();
			//数据的长度
			int length = dp.getLength();
			String s = new String(data, 0, length);
			System.out.println("接收到的数据是：" + s);

		} catch (Exception e) {
			e.printStackTrace();
		}


	}
}
